import socket

import time

from . import tlv_parser


class SocketClient(object):
    tp = tlv_parser.TlvParse()

    def online(self, server_info, data, secret):
        d = self.tp.get_online_data(data, secret)
        return self.socket_client(server_info, d)

    def offline(self, server_info, data, secret):
        d = self.tp.get_offline_data(data, secret)
        return self.socket_client(server_info, d)

    def socket_client(self, server_info, data):
        if server_info["ip"] is None or server_info["port"] is None:
            return
        if data is None:
            return
        result = False
        # address = (server_info["ip"], server_info["port"])
        address = (server_info['ip'], server_info['port'])
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        start = time.clock()
        s.sendto(data, address)
        while True:
            end = time.clock()
            if int(end - start) == 10:
                break
            result, ADDR = s.recvfrom(1024)
            # 若响应为成功，则返回True
            if self.tp.tlv_result_parser(result):
                print("上线成功")
                result = True
        s.close()
        return result


if __name__ == "__main__":
    serverInfo = {}
    serverInfo['ip'] = "192.168.1.199"
    serverInfo['port'] = 2000
    data = {}
    data["username"] = "zyt"
    data["pwd"] = "123456"
    secret = "123456789"
    SocketClient().online(serverInfo, data, secret)
    # 以下为单项测试
    # data=b'123456'
    # SocketClient().socket_client(serverInfo,data)
